var service_common = require("common.js");

//对外公开的方法
module.exports = {
  login: login,
  login2: login2,
  getUserInfo: getUserInfo,
  getUserInfo2: getUserInfo2,
  saveUserInfo: saveUserInfo,
  getUserImage: getUserImage,
  loveAdd: loveAdd,
  loveDrop: loveDrop,
  collectAdd: collectAdd,
  collectDrop: collectDrop,
  getFindUser: getFindUser,
  hideCard: hideCard,
  showCard: showCard,
  validateRedeem: validateRedeem,
  getUserCode: getUserCode,
  getUserHB: getUserHB,
  deleteImage: deleteImage,
  getQun: getQun,
  getZiYuanFaBuPingTai: getZiYuanFaBuPingTai,
  getKeFu1: getKeFu1,
  getKeFu2: getKeFu2,
  addFormId: addFormId,
  getShowTime: getShowTime,
  setUserShareTime: setUserShareTime,
  changeMobileVisible: changeMobileVisible,
  getMobileNumber: getMobileNumber,
  getOpenIdById: getOpenIdById,
  getUserNews: getUserNews,
  setWanrenquan: setWanrenquan,
  getTypeList2: getTypeList2,
  getToken: getToken,
  getTk: getTk
}

/**
 * 登陆
 */ 
function login(cb, shareopenid = 0) {
  var that = this;
  // if (getApp().globalData.openid != undefined && getApp().globalData.openid.length == 28) {
  //   this.getUserInfo(cb);
  //   return;
  // }
  wx.login({
    success: res => {
      console.log(res)
      wx.getSetting({ 
        success(ress) {
          service_common.fetchData(
            service_common.getUrl("user.getOpenid"),
            { code: res.code },
            function (res2) {
              var result = res2.data.data;
         
              if (result.openid != undefined && result.openid.length == 28) {
                console.log(result)
                getApp().globalData.unionid = result.unionid
                getApp().globalData.openid = result.openid;
                getApp().globalData.real_openid = result.openid
                getApp().globalData.session_key = result.session_key;
 
                if (ress.authSetting['scope.userInfo']) {
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                  that.getUserInfo(cb, shareopenid)
                }else{
                  cb(false)
                }
              }
            },
            "GET"
          )
        }
      })
    },
    fail: res => {
      console.log(res)
    }
  })
}

/**
 * 获取用户信息
 */
function getUserInfo(cb, shareopenid = 0) {
  var data = [];
  // if (getApp().globalData.userInfo != undefined) {
  //   service_common.fetchData(service_common.getUrl("user.getUserInfo"),
  //     {
  //       openid: getApp().globalData.openid,
  //       login: 0
  //     },
  //     function (res) {
  //       if (res.data.code == 0) {
  //         getApp().globalData.userInfo = res.data.data;
  //         cb(res.data.data);
  //       }
  //     },
  //     "GET"
  //   );
  //   return;
  // }

  wx.getUserInfo({
    withCredentials: true,
    success: res => {
      console.log("123910-39120321")
      console.log(res)
      data["nickname"] = res.userInfo["nickName"];
      data["headimgurl"] = res.userInfo["avatarUrl"];
      data["city"] = res.userInfo["city"];
      data["country"] = res.userInfo["country"];
      data["sex"] = res.userInfo["gender"];
      data["language"] = res.userInfo["language"];
      data["province"] = res.userInfo["province"];
      // 加密数据
      data["encryptedData"] = res.encryptedData;
      data["iv"] = res.iv;
      data["signature"] = res.signature;
    },
    complete: res => {
      data["openid"] = getApp().globalData.openid;
      data["sessionkey"] = getApp().globalData.session_key;
      data["shareopenid"] = shareopenid;
      data["login"] = 1;
      console.log(data)
      wx.getLocation({
        success: function (res2) {
          console.log("获取定位成功", res2);
          data["latitude"] = res2.latitude;
          data["longitude"] = res2.longitude;
        },
        complete: res2 => {
          //获取数据
          console.log(data)
          service_common.fetchData(service_common.getUrl("user.getUserInfo"),
            data,
            function (res) {
              if (res.data.code == 0) {
                console.log(res.data.data)
                wx.setStorageSync('token__', res.data.data.token)
                wx.setStorageSync('token_key', res.data.data.token_key)
                getApp().globalData.openid = res.data.data.openid
                getApp().globalData.userInfo = res.data.data;
                console.log(res.data.data)
                cb(res.data.data);
              }
            },
            "GET"
          );
        }
      })
    }
  })
}

/**
 * 保存用户信息
 */
function saveUserInfo(data, cb) {
  service_common.fetchData(service_common.getUrl("user.saveUserInfo"),
    data,
    function (res) {
      if (res.data.code == 0) {
        if (cb && typeof cb == "function") {
          cb(res);
        }
      }
    },
    "POST"
  );
  return;
}

/**
 * 获取用户图片
 */
function getUserImage(openid, cb) {
  service_common.fetchData(
    service_common.getUrl("user.getUserImage"),
    {
      openid: openid
    },
    function (res) {
      cb(res)
    },
    "GET"
  )
}

/**
 * 用户点赞
 */
function loveAdd(openid, cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserLoveAdd"),
    {
      openid: getApp().globalData.openid,
      openid2: openid
    },
    function (res) {
      cb(res);
    },
    "GET"
  )
}

/**
 * 取消点赞
 */
function loveDrop(openid, cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserLoveDrop"),
    {
      openid: getApp().globalData.openid,
      openid2: openid
    },
    function (res) {
      cb(res)
    },
    "GET"
  )
}


/**
 * 用户点赞
 */
function collectAdd(openid, cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserCollectAdd"),
    {
      openid: getApp().globalData.openid,
      openid2: openid
    },
    function (res) {
      cb(res)
    },
    "GET", true
  )
}

/**
 * 取消点赞
 */
function collectDrop(openid, cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserCollectDrop"),
    {
      openid: getApp().globalData.openid,
      openid2: openid
    },
    function (res) {
      cb(res)
    },
    "POST"
  )
}

/**
 * 获取找合作的一个用户
 */
function getFindUser(cb) {
  service_common.fetchData(
    service_common.getUrl("user.getFindUser"),
    {
      openid: getApp().globalData.openid,
    },
    function (res) {
      cb(res)
    },
    "GET"
  )
}

/**
 * 用户隐藏名片
 */
function hideCard(cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserHideCard"),
    {
      openid: getApp().globalData.openid,
    },
    function (res) {
      cb(res)
    },
    "POST"
  )
}

/**
 * 用户展示名片
 */
function showCard(cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserShowCard"),
    {
      openid: getApp().globalData.openid,
    },
    function (res) {
      cb(res)
    },
    "GET"
  )
}

/**
 * 检验用户兑换码
 */
function validateRedeem(redeem, cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserRedeem"),
    {
      openid: getApp().globalData.openid,
      redeem: redeem
    },
    function (res) {
      cb(res)
    },
    "GET", true
  )
}
/**
 * 获取个人专属码
 */
function getUserCode() {
  service_common.fetchData(
    service_common.getUrl("user.getUserCodeList"),
    {
      uid: getApp().globalData.userInfo.id,
    },
    function (res) {
      var array = [];
        for(var i = 0; i < res.data.data.length ; i++){
          array.push(res.data.data[i]);
        }
        wx.previewImage({
          urls: array
        })
    },
    "GET", true
  )
}

/**
 * 获取个人海报图
 */
function getUserHB() {
  console.log(service_common.getUrl("user.getUserHB") + "?uid=" + getApp().globalData.userInfo.id + "&openid=" + getApp().globalData.openid + "&version=" + getApp().globalData.version);
  wx.previewImage({
    urls: [service_common.getUrl("user.getUserHB") + "?uid=" + getApp().globalData.userInfo.id + "&openid=" + getApp().globalData.openid + "&version=" + getApp().globalData.version],
  })
}

/**
 * 获取资源发布平台
 */
function getZiYuanFaBuPingTai() {
  wx.previewImage({
    urls: [service_common.getUrl("user.getZiYuanFaBuPingTai") + "?time=" + new Date().getTime()],
  })
}

/**
 * 获取群图片
 */
function getQun() {
  wx.previewImage({
    urls: [service_common.getUrl("user.getQun") + "?time=" + new Date().getTime()],
  })
}
/**
 * 获取客服1
 */
function getKeFu1() {
  wx.previewImage({
    urls: [service_common.getUrl("user.getKeFu1") + "?time=" + new Date().getTime()],
  })
}
/**
 * 获取客服2
 */
function getKeFu2() {
  wx.previewImage({
    urls: [service_common.getUrl("user.getKeFu2") + "?time=" + new Date().getTime()],
  })
}

function deleteImage(id, cb) {
  service_common.fetchData(
    service_common.getUrl("user.deleteImage"),
    {
      id: id,
    },
    function (res) {
      cb(res)
    },
    "POST"
  )
}

/**
 * 添加FormId
 */
function addFormId(formid) {
  console.log("formid："+formid);
  service_common.fetchData(
    service_common.getUrl("user.setFromId"),
    {
      openid: getApp().globalData.openid,
      formid: formid,
    },
    function (res) {
      //cb(res)
      console.log(res)
    },
    "POST"
  )
}

/**
 * 获取展示时间
 */
function getShowTime(cb) {
  service_common.fetchData(
    service_common.getUrl("user.getShowTime"),
    {
      openid: getApp().globalData.openid,
    },
    function (res) {
      cb(res)
    },
    "GET"
  )
} 
/**
 * 更新用户的分享时间
 */
function setUserShareTime(cb) {
  service_common.fetchData(
    service_common.getUrl("user.setUserShareTime"),
    {
      openid: getApp().globalData.openid,
    },
    function (res) {
      cb(res)
    },
    "POST", true
  )
}
function changeMobileVisible(mobile_visible, cb) {
  service_common.fetchData(
    service_common.getUrl("user.changeMobileVisible"),
    {
      openid: getApp().globalData.openid,
      mobile_visible: mobile_visible
    },
    function (res) {
      cb(res)
    },
    "POST", true
  )
}
function getMobileNumber(encryptedData, iv, cb) {
  service_common.fetchData(
    service_common.getUrl("user.getMobileNumber"),
    {
      openid: getApp().globalData.openid,
      session_key: getApp().globalData.session_key,
      encryptedData: encryptedData,
      iv: iv
    },
    function (res) {
      cb(res)
    },
    "GET", true
  )
}
function getOpenIdById(uid, cb) { 
  service_common.fetchData(
    service_common.getUrl("user.getOpenIdById"),
    {
      uid: uid,
    },
    function (res) {
      cb(res)
    },
    "GET", true
  )
}

/**
 * 获取用户新消息
 */
function getUserNews(cb) {
  service_common.fetchData(
    service_common.getUrl("user.getUserNews"),
    {
      openid: getApp().globalData.openid,
    },
    function (res) {
      cb(res)
    },
    "POST", true
  )
}

/* 
*发布万人圈
*/
function setWanrenquan(content, file,Type,cb) {
  service_common.fetchData(
    service_common.getUrl("user.setWanrenquan"),
    {
      openid: getApp().globalData.openid,
      content: content,
      files: file,
      type: Type,
      is_hot:0
    },
    function (res) {
      cb(res)
    },
    "POST", true
  )
}

//获取发布广场消息分类
function getTypeList2(cb) {
  service_common.fetchData(
    service_common.getUrl("user.getTypeList2"),
    {
      version: getApp().globalData.version
    },
    function (res) {
      cb(res)
    },
    "POST", true
  )
}

// 个人中心
function login2(cb, shareopenid = 0) {
  var that = this;
  if (getApp().globalData.openid != undefined && getApp().globalData.openid.length == 28) {
    this.getUserInfo2(cb);
    return;
  }
  wx.login({
    success: res => {
   
      service_common.fetchData(
        service_common.getUrl("user.getOpenid"),
        { code: res.code },
        function (res2) {
          var result = res2.data.data;
          if (result.openid != undefined && result.openid.length == 28) {
            getApp().globalData.openid = result.openid;
            getApp().globalData.session_key = result.session_key;
            that.getUserInfo2(cb, shareopenid);
          } else {
            wx.showModal({
              title: '提示',
              content: '登录失败，请重试',
              showCancel: false,
              success: res => {
              }
            })
          }
        },
        "GET"
      )
    },
    fail: res => {
      console.log(res)
    }
  })
}

function getUserInfo2(cb, shareopenid = 0) {
  var data = [];

  if (getApp().globalData.userInfo != undefined) {
    console.log(getApp().globalData.userInfo)
    service_common.fetchData(service_common.getUrl("user.getUserInfo"),
      {
        openid: getApp().globalData.userInfo.openid,
        login: 0 
      },
      function (res) {
        if (res.data.code == 0) {
          getApp().globalData.userInfo = res.data.data;
          cb(res.data.data);
        }
      },
      "GET"
    );
    return;
  }

  wx.getUserInfo({
    withCredentials: true,
    success: res => {
      console.log('bgbgbgbgbgbgbgbgb')
      data["nickname"] = res.userInfo["nickName"];
      data["headimgurl"] = res.userInfo["avatarUrl"];
      data["city"] = res.userInfo["city"];
      data["country"] = res.userInfo["country"];
      data["sex"] = res.userInfo["gender"];
      data["language"] = res.userInfo["language"];
      data["province"] = res.userInfo["province"];
      // 加密数据
      data["encryptedData"] = res.encryptedData;
      data["iv"] = res.iv;
      data["signature"] = res.signature;
    },
    complete: res => {
      data["openid"] = getApp().globalData.openid;
      data["sessionkey"] = getApp().globalData.session_key;
      data["shareopenid"] = shareopenid;
      data["login"] = 1;
      wx.getLocation({
        success: function (res2) {
          console.log("获取定位成功", res2);
          data["latitude"] = res2.latitude;
          data["longitude"] = res2.longitude;
        },
        complete: res2 => {
          //获取数据
          service_common.fetchData(service_common.getUrl("user.getUserInfo"),
            data,
            function (res) {
              if (res.data.code == 0) {
                console.log(res.data.data)
                wx.setStorageSync('token__', res.data.data.token)
                wx.setStorageSync('token_key', res.data.data.token_key)
                getApp().globalData.userInfo = res.data.data;
                cb(res.data.data);
              }
            },
            "GET"
          );
        }
      })
    }
  })
}
// 获取小官网token
function getToken(openid,cb){
  var token = wx.getStorageSync('token')
  console.log(token)
  // if (wx.getStorageSync('token') == '' || wx.getStorageSync('token') == null) {//第一次获取
  //   getTk(openid,function(res){
  //     wx.setStorageSync('token', res.data.data.token)
  //     token = res.data.data.token
  //     wx.setStorageSync('token_deadline', Date.now() + 7000000);
  //   })
  // } else if (wx.getStorageSync('token') != '' && (Date.now() - wx.getStorageSync('token_deadline') >= 0)) {//有缓存，token即将过期
  //   getTk(openid, function (res) {
  //     wx.setStorageSync('token', res.data.data.token)
  //     token = res.data.data.token
  //     wx.setStorageSync('token_deadline', Date.now() + 7000000);
  //   }) 
  // }
  service_common.fetchData(
    service_common.getUrl("website.getToken"),
    { openid: openid },
    function (res) {
      wx.setStorageSync('token', res.data.data.token)
      if(cb){
        cb(res.data.data.token)
      }
      
    },
    "GET"
  )
  
}
function getTk(openid){
  service_common.fetchData(
    service_common.getUrl("website.getToken"),
    { openid: openid },
    function (res) {
      return res.data.data.token
    },
    "GET"
  )
}